package com.senseauto.camera2record.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.Image;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class PhotoUtil {
    private static final String TAG = "PhotoUtil";

    public static void saveImage(Image mImage) {
        Log.e("6666", "saveImage: ");
        ByteBuffer prebuffer = ByteBuffer.allocate(16);
        prebuffer.putInt(mImage.getWidth())
                .putInt(mImage.getHeight())
                .putInt(mImage.getPlanes()[1].getPixelStride())
                .putInt(mImage.getPlanes()[1].getRowStride());
        File file = new File(Environment.getExternalStorageDirectory(),
                "cacheImage");

        FileOutputStream output = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        ByteBuffer buffer = null;
        byte[] bytes = null;
        try {
            output = new FileOutputStream(file);
            output.write(prebuffer.array()); // write meta information to file
            // Now write the actual planes.
            for (int i = 0; i < 3; i++) {
                buffer = mImage.getPlanes()[i].getBuffer();
                bytes = new byte[buffer.remaining()]; // makes byte array large enough to hold image
                buffer.get(bytes); // copies image from buffer to byte array
                output.write(bytes);    // write the byte array to file
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 根据byte数组生成文件
     *
     * @param bytes 生成文件用到的byte数组
     */
    public static void createFileWithByte(Context context, byte[] bytes, int frame) {
        // TODO Auto-generated method stub
        /**
         * 创建File对象，其中包含文件所在的目录以及文件的命名
         */
        File file = new File(context.getExternalFilesDir("image"),
                "cacheImage_"+frame+".yuv");
        Log.e(TAG, "createFileWithByte: " + file.getAbsolutePath());
        // 创建FileOutputStream对象
        FileOutputStream outputStream = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 如果文件存在则删除
            if (file.exists()) {
                file.delete();
            }
            // 在文件系统中根据路径创建一个新的空文件
            file.createNewFile();
            // 获取FileOutputStream对象
            outputStream = new FileOutputStream(file);
            // 获取BufferedOutputStream对象
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 往文件所在的缓冲输出流中写byte数据
            bufferedOutputStream.write(bytes);
            // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
            bufferedOutputStream.flush();
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

    private boolean hah = false;
    private boolean isone = true;


    public static byte[] i420ToNV21(byte[] i420bytes, int width, int height) {
        byte[] nv21bytes = new byte[i420bytes.length];
        int total = width * height; //Y数据的长度
        int nLen = total / 4;  //U、V数据的长度
        System.arraycopy(i420bytes, 0, nv21bytes, 0, total);

        for (int i = 0; i < nLen; i++) {
            byte u = i420bytes[total + i];
            byte v = i420bytes[total + nLen + i];
            nv21bytes[total + i * 2] = v;
            nv21bytes[total + i * 2 + 1] = u;
        }
        return nv21bytes;
    }

    public static void I420ToNV21(final byte[] input, final byte[] output, final int width, final int height) {
        //long startMs = System.currentTimeMillis();
        byte[] nv21bytes = new byte[input.length];
        final int frameSize = width * height;
        final int qFrameSize = frameSize / 4;
        final int tempFrameSize = frameSize * 5 / 4;

        System.arraycopy(input, 0, output, 0, frameSize); // Y

        for (int i = 0; i < qFrameSize; i++) {
            output[frameSize + i * 2] = input[tempFrameSize + i]; // Cb (U)
            output[frameSize + i * 2 + 1] = input[frameSize + i]; // Cr (V)
        }
    }

    public static void saveToSDCard(File file, Bitmap bmp) {
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, bos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

//        String path = file.getAbsolutePath();
//        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//        Uri contentUri = Uri.fromFile(file);
//        mediaScanIntent.setData(contentUri);
//        AutoApplication.getContext().sendBroadcast(mediaScanIntent);
//
//        if (Build.VERSION.SDK_INT >= 19) {
//            MediaScannerConnection.scanFile(AutoApplication.getContext(), new String[]{path}, null, null);
//        }
    }


//            long start = System.currentTimeMillis();
//            byte[] dataNV21 = i420ToNV21(data, mImageWidth, mImageHeight);
//            Log.e(TAG, "onPreviewFrame: " + (System.currentTimeMillis() - start));
//
//            if (dataNV21.length != mImageWidth * mImageHeight * 3 / 2) {
//                return;
//            }


//            if (isone){
//                mHandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        hah = true;
//                        isone = false;
//                    }
//                } , 3000);
//            }
//
//            if (hah){
//                createFileWithByte(data);
//                hah = false;
//            }
//            synchronized (mImageDataLock) {
//                System.arraycopy(dataNV21, 0, mImageData, 0, dataNV21.length);
//            }
}
